package com.hzhh123.download;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hzhh123.download.service.DownloadService;
import com.hzhh123.download.utils.db.DbHelper;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.SpeedCalculator;
import com.liulishuo.okdownload.core.Util;
import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed;
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class SingleDownloadActivity extends AppCompatActivity {

    private static final String TAG = "SingleDownloadActivity";
    private DownloadTask task;
    private int REQUEST_CODE_EXTERNAL_STORAGE = 20;
    private ImageView start,pause,download;
    private TextView speed,size,totalSize,space,size_str,create_time;
    private ProgressBar progressBar;
    private DownloadReceiver receiver;
    private TextView refresh;
    private int actionStatus=2;//1-开始 2-暂停
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download1);
        initUI();
        checkExtrnalStorage();
        IntentFilter filter = new IntentFilter();
        receiver=new DownloadReceiver();
        filter.addAction("com.hzhh123.download1");
        registerReceiver(receiver, filter);
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                start.setVisibility(View.GONE);
                pause.setVisibility(View.VISIBLE);
                download.setVisibility(View.GONE);
               // download();
                progressBar.setVisibility(View.VISIBLE);
                Intent intent=new Intent(SingleDownloadActivity.this,DownloadService.class);
                intent.putExtra("filename","single-test.apk");
                String url = "https://cdn.llscdn.com/yy/files/tkzpx40x-lls-LLS-5.7-785-20171108-111118.apk";
                intent.putExtra("url",url);
                intent.putExtra("id","1");
                startService(intent);
            }
        });
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              // download();
                actionStatus=2;
                start.setVisibility(View.GONE);
                pause.setVisibility(View.VISIBLE);
                Intent intent=new Intent(SingleDownloadActivity.this,DownloadService.class);
                intent.putExtra("filename","single-test.apk");
                String url = "https://cdn.llscdn.com/yy/files/tkzpx40x-lls-LLS-5.7-785-20171108-111118.apk";
                intent.putExtra("url",url);
                intent.putExtra("id","1");
                startService(intent);
            }
        });

        refresh.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 actionStatus=2;
                 start.setVisibility(View.GONE);
                 pause.setVisibility(View.VISIBLE);
                 refresh.setVisibility(View.GONE);
                 Intent intent=new Intent(SingleDownloadActivity.this,DownloadService.class);
                 intent.putExtra("filename","single-test.apk");
                 String url = "https://cdn.llscdn.com/yy/files/tkzpx40x-lls-LLS-5.7-785-20171108-111118.apk";
                 intent.putExtra("url",url);
                 intent.putExtra("id","1");
                 startService(intent);
             }
         });
        //暂停
        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                task.cancel();
                MyApplication.downloadTaskHashMap.get("1").cancel();
                actionStatus=1;
                start.setVisibility(View.VISIBLE);
                pause.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver!=null){
            unregisterReceiver(receiver);
        }
    }

    private void download(){
        progressBar.setVisibility(View.VISIBLE);
        start.setVisibility(View.GONE);
        pause.setVisibility(View.VISIBLE);
        String filename = "single-test";
        String url = "https://cdn.llscdn.com/yy/files/tkzpx40x-lls-LLS-5.7-785-20171108-111118.apk";
        File parentFile = getExternalCacheDir();
        task = new DownloadTask.Builder(url, parentFile)
                .setFilename(filename)
                .setMinIntervalMillisCallbackProcess(30) // 下载进度回调的间隔时间（毫秒）
                .setPassIfAlreadyCompleted(false)// 任务过去已完成是否要重新下载
                .setPriority(10)
                .build();
        task.enqueue(new DownloadListener4WithSpeed() {
            @Override
            public void taskStart(@NonNull DownloadTask task) {
                Log.d(TAG, "taskStart: "+task.getId());
            }

            @Override
            public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {
                Log.d(TAG, "connectStart: ");
            }

            @Override
            public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {
                Log.d(TAG, "connectEnd: ");
            }

            @Override
            public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
                Log.d(TAG, "infoReady: ");
            }

            @Override
            public void progressBlock(@NonNull DownloadTask task, int blockIndex, long currentBlockOffset, @NonNull SpeedCalculator blockSpeed) {
                Log.d(TAG, "progressBlock: ");
            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
                Log.d(TAG, "progress: "+taskSpeed.speed());
                speed.setText(taskSpeed.speed());
                float percent=((float)task.getInfo().getTotalOffset()/task.getInfo().getTotalLength())*100;
                System.out.println((int)percent);
                size.setText(Util.humanReadableBytes(task.getInfo().getTotalLength(),true) +"("+(int)percent+"%)");
                progressBar.setProgress((int)percent);
            }

            @Override
            public void blockEnd(@NonNull DownloadTask task, int blockIndex, BlockInfo info, @NonNull SpeedCalculator blockSpeed) {
                Log.d(TAG, "blockEnd: ");
            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull SpeedCalculator taskSpeed) {
                float percent=((float)task.getInfo().getTotalOffset()/task.getInfo().getTotalLength())*100;
                System.out.println((int)percent);
                System.out.println(cause==EndCause.CANCELED);
                if((int)percent==100){
                    String totalSize = Util.humanReadableBytes(task.getInfo().getTotalLength(), true).toString();
                    size.setText(totalSize +"("+(int)percent+"%)");
                    progressBar.setProgress((int)percent);
                    start.setVisibility(View.GONE);
                    pause.setVisibility(View.GONE);
                    download.setVisibility(View.GONE);
                    speed.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    space.setVisibility(View.VISIBLE);
                    size_str.setVisibility(View.VISIBLE);
                    create_time.setVisibility(View.VISIBLE);
                    size.setVisibility(View.GONE);
                    size_str.setText(totalSize);
                    create_time.setText(DateFormat.format("yyyy/MM/dd",new Date()));
                }
                Log.d(TAG, "cause: "+cause.toString());
                Log.d(TAG, "taskEnd: ");
            }
        });
    }

    private void initUI(){
        refresh=findViewById(R.id.refresh);
        speed=findViewById(R.id.speed);
        size=findViewById(R.id.size);
        start=findViewById(R.id.start);
        pause=findViewById(R.id.pause);
        download=findViewById(R.id.download);
        create_time=findViewById(R.id.create_time);
        space=findViewById(R.id.space);
        size_str=findViewById(R.id.size_str);
        progressBar=findViewById(R.id.progressBar);
        progressBar.setVisibility(View.GONE);
    }


    class DownloadReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.hzhh123.download1")){
                String speedS=intent.getStringExtra("speed");
                speed.setText(speedS);
                String sizeS=intent.getStringExtra("size");
                String totalSize=intent.getStringExtra("totalSize");
                size.setText(sizeS);
                int pencent=intent.getIntExtra("percent",0);
                progressBar.setProgress(pencent);
                int status=intent.getIntExtra("status",0);
                System.out.println("status="+status);
                if(status==1){
                    download.setVisibility(View.GONE);
                    refresh.setVisibility(View.GONE);
                    if(actionStatus==1){
                        start.setVisibility(View.VISIBLE);
                        pause.setVisibility(View.GONE);
                    }else{
                        start.setVisibility(View.GONE);
                        pause.setVisibility(View.VISIBLE);
                    }
                }
                if (status==2){//完成
                    start.setVisibility(View.GONE);
                    pause.setVisibility(View.GONE);
                    download.setVisibility(View.GONE);
                    speed.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    space.setVisibility(View.VISIBLE);
                    size_str.setVisibility(View.VISIBLE);
                    create_time.setVisibility(View.VISIBLE);
                    size.setVisibility(View.GONE);
                    refresh.setVisibility(View.GONE);
                    size_str.setText(totalSize);
                    create_time.setText(DateFormat.format("yyyy/MM/dd",new Date()));
                }
                if(status==3){
                    //超时，出错
                    start.setVisibility(View.GONE);
                    pause.setVisibility(View.GONE);
                    progressBar.setVisibility(View.GONE);
                    refresh.setVisibility(View.VISIBLE);
                    MyApplication.downloadTaskHashMap.get("1").cancel();
                }
            }
        }
    }

    /**
     * 检查外部scard读写权限
     */
    private void checkExtrnalStorage(){
        //首先判断用户手机的版本号 如果版本大于6.0就需要动态申请权限
        //如果版本小于6.0就直接去扫描二维码
        if(Build.VERSION.SDK_INT>23){
            //说明是android6.0之前的
            //添加动态权限申请
            //1.定义一个数组，用来装载申请的权限
            String[] permissons={
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
            };
            //2.判断这些权限有没有申请，没有申请的话，就把没有申请的权限放到一个数组里面
            ArrayList<String> deniedPermissions=new ArrayList<String>();
            for(String permission:permissons){
                int i = ContextCompat.checkSelfPermission(this, permission);
                if(PackageManager.PERMISSION_DENIED==i){
                    //说明权限没有被申请
                    deniedPermissions.add(permission);
                }
            }
            if(deniedPermissions.size()==0){
                //说明是android6.0之前的
                return;
            }
            //当你不知道数组多大的时候，就可以先创建一个集合，然后调用集合的toArray方法需要传递一个数组参数，这个数组参数的长度
            //设置成跟集合一样的长度
            String[] strings = deniedPermissions.toArray(new String[permissons.length]);
            //3.去申请权限
            ActivityCompat.requestPermissions(this,strings,REQUEST_CODE_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }



}
